package iblobs

import (
	"context"
	"crypto/sha256"
	"fmt"

	"gitee.com/djaf/my-certs/app/classes/blobs"
	"gitee.com/djaf/my-certs/app/data/dxo"
	"gitee.com/djaf/my-certs/app/data/entity"
	"gitee.com/djaf/my-certs/app/web/dto"
	"github.com/starter-go/base/lang"
)

// BlobServiceImpl ...
type BlobServiceImpl struct {

	//starter:component

	_as func(blobs.Service) //starter:as("#")

	Dao blobs.DAO //starter:inject("#")

}

func (inst *BlobServiceImpl) _impl() blobs.Service {
	return inst
}

func (inst *BlobServiceImpl) prepareItemToWrite(item *entity.BLOB) error {

	data := item.Content
	sum := sha256.Sum256(data)
	hex := lang.HexFromBytes(sum[:])

	item.Size = len(data)
	item.SHA256SUM = hex
	return nil
}

// Insert ...
func (inst *BlobServiceImpl) Insert(ctx context.Context, item1 *dto.BLOB) (*dto.BLOB, error) {
	item2, err := blobs.ConvertD2E(item1)
	if err != nil {
		return nil, err
	}

	err = inst.prepareItemToWrite(item2)
	if err != nil {
		return nil, err
	}

	item3, err := inst.Dao.Insert(nil, item2)
	if err != nil {
		return nil, err
	}

	return blobs.ConvertE2D(item3)
}

// Update ...
func (inst *BlobServiceImpl) Update(ctx context.Context, id dxo.BlobID, item *dto.BLOB) (*dto.BLOB, error) {
	return nil, fmt.Errorf("no impl")
}

// Remove ...
func (inst *BlobServiceImpl) Remove(ctx context.Context, id dxo.BlobID) error {
	return fmt.Errorf("no impl")
}

// Find ...
func (inst *BlobServiceImpl) Find(ctx context.Context, id dxo.BlobID) (*dto.BLOB, error) {
	ent, err := inst.Dao.Find(nil, id)
	if err != nil {
		return nil, err
	}
	return blobs.ConvertE2D(ent)
}

// List ...
func (inst *BlobServiceImpl) List(ctx context.Context, q *blobs.Query) ([]*dto.BLOB, error) {
	return nil, fmt.Errorf("no impl")
}
